package com.welbell.utlis;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

public class VoiceAnnouncements implements TextToSpeech.OnInitListener {

    private static final String TAG = VoiceAnnouncements.class.getName();
    public static VoiceAnnouncements mVoiceAnnouncements = null;
    private TextToSpeech mTextToSpeech = null;

    public static VoiceAnnouncements getInstance() {
        synchronized (VoiceAnnouncements.class) {
            if (mVoiceAnnouncements == null) {
                mVoiceAnnouncements = new VoiceAnnouncements();
            }
        }
        return mVoiceAnnouncements;
    }

    public void init(Context context) {
        TLog.d(TAG, "初始化");
        mTextToSpeech = new TextToSpeech(context, VoiceAnnouncements.this);
    }


    /**
     * 设置语音播放参数（设置-1将不起作用）
     *
     * @param pitch      音调
     * @param speechRate 语速
     */
    public void setParameter(float pitch, float speechRate) {
        TLog.d(TAG, "配置音调音速");
        if (mTextToSpeech == null) {
            return;
        }
        if (pitch != -1)
            //设置音调
            mTextToSpeech.setPitch(pitch);
        if (speechRate != -1)
            //设置语速，1.0为正常语速
            mTextToSpeech.setSpeechRate(speechRate);
    }

    /**
     * 设置播放内容
     *
     * @param isCover 是否覆盖式播放
     * @param text    播放的内容
     */
    public void speak(boolean isCover, String text) {
        TLog.d(TAG, "text11111: " + text);
        if (mTextToSpeech == null) {
            return;
        }
        TLog.d(TAG, "text222222: " + text);
        if (isCover) {
            mTextToSpeech.stop();
        }
        TLog.d(TAG, "text33333333333: " + text);
        mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    /**
     * 回调函数
     *
     * @param status
     */
    @Override
    public void onInit(int status) {
        //设置朗读语言
        int supported = mTextToSpeech.setLanguage(Locale.CHINA);
        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            Log.e(TAG, "onInit: 不支持当前语言");
        }
    }
}
